import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  BetaSchemaForm,
  FooterToolbar,
  GridContent,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { Button, Drawer, Dropdown, Form, Input, Popconfirm, message } from 'antd';
import React, { useRef, useState } from 'react';
import { addEnv, batchDelEnv, getEnvPage, updateEnv } from './service';
import { useModel } from '@umijs/max';

const handleRemove = async (idList: any[], projectId: any) => {
  const hide = message.loading('正在删除');
  if (!idList) return true;

  try {
    const res = await batchDelEnv({
      idList,
      projectId,
    });
    hide();
    if (res.code == 0) {
      message.success('删除成功，即将刷新');
      return true;
    } else {
      message.error('删除失败，请重试');
      return false;
    }
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList: React.FC = () => {
  const [addForm] = Form.useForm()
  const [editForm] = Form.useForm()
  const actionRef = useRef<ActionType>();
  const [selectedRowsState, setSelectedRows] = useState<any[]>([]);
  const { initialState } = useModel('@@initialState');

  const columns: ProColumns<any>[] = [
    {
      title: '序号',
      valueType: 'indexBorder',
    },
    {
      title: '环境名称',
      dataIndex: 'name'
    },
    {
      title: '协议',
      dataIndex: 'protocol',
      hideInSearch: true,
      valueType: 'select',
      initialValue: 'http',
      valueEnum: {
        http: { text: 'http' },
        https: { text: 'https' }
      }
    },
    {
      title: '环境域名',
      dataIndex: 'domain',
      hideInSearch: true,
      renderFormItem(schema, config, form, action) {
        let protocol = form.getFieldValue('protocol')
        let beforeStr = protocol ? protocol + '://' : ''
        return <Input addonBefore={beforeStr} />
      },
    },
    {
      title: '端口',
      dataIndex: 'port',
      hideInSearch: true,
      fieldProps: {
        step: '1',
        max: 65536,
        style: {
          width: 200
        },

      }
    },
    {
      title: '描述',
      dataIndex: 'description',
      hideInSearch: true,
      valueType: 'textarea',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreate',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'gmtModified',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record: any) => [
        <BetaSchemaForm<any>
          key="edit"
          layoutType="ModalForm"
          form={editForm}
          modalProps={{
            title: '编辑环境',
            width: 600,
          }}
          columns={columns as any}
          trigger={<a
            key="config"
            onClick={() => {
              editForm.setFieldsValue(record)
            }}
          >
            编辑
          </a>}
          onFinish={async (values) => {
            const hide = message.loading('正在保存');

            try {
              const res = await updateEnv({
                ...record,
                ...values
              });
              hide();
              if (res.code == 0) {
                message.success('保存成功');
                actionRef.current?.reload()
                return true;
              } else {
                message.error('保存失败请重试！');
                return false;
              }
            } catch (error) {
              hide();
              message.error('保存失败请重试！');
              return false;
            }
          }}
        />,
        <Popconfirm key='del' title="是否要删除此行？" onConfirm={async () => {
          const res = await handleRemove([record?.id], initialState?.currentProject?.id)
          if (res) {
            actionRef.current?.reload()
          }
          return res
        }}>
          <a onClick={() => {
          }}>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        rowKey="id"
        search={{
        }}
        actionRef={actionRef}
        toolBarRender={() => [
          <BetaSchemaForm<any>
            key={'add'}
            layoutType="ModalForm"
            form={addForm}
            modalProps={{
              title: '新增环境',
              width: 600,
            }}
            columns={columns as any}
            trigger={<Button type='primary' onClick={() => {
              addForm.resetFields()
            }}
              icon={<PlusOutlined />}>新增</Button>}
            onFinish={async (values) => {
              const hide = message.loading('正在添加');

              try {
                const res = await addEnv({ ...values, projectId: initialState?.currentProject?.id });
                hide();
                if (res.code == 0) {
                  message.success('添加成功');
                  actionRef.current?.reload()
                  return true;
                } else {
                  message.error('添加失败请重试！');
                  return false;
                }

              } catch (error) {
                hide();
                message.error('添加失败请重试！');
                return false;
              }
            }}
          />,
        ]}
        request={async ({ current, pageSize, ...params }) => {
          const res = await getEnvPage({
            current,
            pageSize,
            projectId: initialState?.currentProject?.id,
            ...params
          })

          return {
            data: res?.data?.currentData || [],
            total: res?.data?.totalPage
          }
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys: selectedRowsState.map((row: any) => row.id),
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项
            </div>
          }
        >
          <Popconfirm key='del' title={`是否要批量删除 ${selectedRowsState.length} 条？`} onConfirm={async () => {
            const res = await handleRemove(selectedRowsState.map((row: any) => row.id), initialState?.currentProject?.id);
            if (res) {
              actionRef.current?.reload()
              setSelectedRows([]);
            }
          }}>
            <Button danger>
              批量删除
            </Button>
          </Popconfirm>

        </FooterToolbar>
      )}


    </PageContainer>
  );
};

export default TableList;
